# myproject/celery.py
import os
from celery import Celery
from celery.signals import after_setup_logger
import logging

#配置Django的settings模块，celery会自动读取settings模块的配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oaback.settings')

app = Celery('oaback')

# 日志配置（可选：仅在 worker 启动时配置一次日志）
@after_setup_logger.connect
def setup_celery_logger(logger, *args, **kwargs):
    handler = logging.FileHandler('celery.log')  # 输出到文件
    formatter = logging.Formatter(
        '[%(asctime)s: %(levelname)s/%(processName)s] %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)

#配置从settings.py 中读取配置信息,所有的Celery开头的配置信息以CELERY_开头
app.config_from_object('django.conf:settings', namespace='CELERY')

#自动发现任务，任务可以在app/tasks.py中定义
app.autodiscover_tasks()

# 运行：celery -A oaback worker -l info --pool gevent

# 测试任务
@app.task(bind=True,ignore_result=True)
def test_task(self):
    # print(f'requset:{self.request}')
    print('hello')
